using System;
using System.IO;
using System.Security.Cryptography;

namespace SortMyPictures
{
    public class FileHash
    {
        /// <summary>
        /// Computes the M d5 hash.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static string ComputeMD5Hash(string fileName)
        {
            return ComputeHash(fileName, new MD5CryptoServiceProvider());
        }

        /// <summary>
        /// Computes the SH a1 hash.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public static string ComputeSHA1Hash(string fileName)
        {
            return ComputeHash(fileName, new SHA1CryptoServiceProvider());
        }

        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <returns></returns>
        public static string ComputeHash(string fileName, HashAlgorithm
                                                              hashAlgorithm)
        {
            FileStream stmcheck = File.OpenRead(fileName);
            if (stmcheck.Length > 1024000)
            {
                byte[] firstBytes = new byte[1024000];
                stmcheck.Read(firstBytes, 0, 1024000);
                try
                {
                    byte[] hash = hashAlgorithm.ComputeHash(firstBytes);
                    string computed = BitConverter.ToString(hash).Replace("-", "");
                    return computed;
                }
                finally
                {
                    firstBytes = null;
                    stmcheck.Close();
                }
            }
            else
            {
                try
                {
                    byte[] hash = hashAlgorithm.ComputeHash(stmcheck);
                    string computed = BitConverter.ToString(hash).Replace("-", "");
                    return computed;
                }
                finally
                {
                    stmcheck.Close();
                }
            }
        }
    }
}